package com.webapps.tvprogram.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.webapps.tvprogram.R;
import com.webapps.tvprogram.data.local.Program;
import com.webapps.tvprogram.utils.GlobalInfo;
import com.webapps.tvprogram.utils.InitResourcesTask;
import com.webapps.tvprogram.utils.MyXmlParserTaskCallback;

public class MainActivity extends Activity {

    private static MainActivity parentActivity;
    private ArrayList<Program> programsData;
    private List<String> favouritesList;
    private static final String TAG = "TvProgram.MainActivity";
    public static final String PROGRAMS_FAV_OPT = "programs_fav_opt";
    public static final String PROGRAM_PREF_TAG = "program";
    private MyXmlParserTaskCallback callback;
    private OnClickListener menuListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.program :
                    prepareStartProgramsList();
                    break;
                case R.id.options :
                    Toast.makeText(MainActivity.this, "Under development", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.about :
                    Toast.makeText(MainActivity.this, "By PASU", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.exit :
                    MainActivity.this.finish();
                    break;
            }
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parentActivity = this;
        prepareCallback();
        setContentView(R.layout.starting_screen);
        prepareStartingDialog();
        loadSharedPref();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private void prepareStartProgramsList() {
        final Resources r = getResources();
        final CharSequence[] items = {r.getString(R.string.prog_list_dial_fav), r.getString(R.string.prog_list_dial_all)};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(r.getString(R.string.prog_list_dial_title));
        builder.setItems(items, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int item) {
                // Toast.makeText(this, items[item], Toast.LENGTH_SHORT).show();
                if ((r.getString(R.string.prog_list_dial_fav)).equalsIgnoreCase(items[item].toString())) {
                    if (favouritesList == null || favouritesList.size() == 0) {
                        Toast
                                .makeText(MainActivity.this, r.getString(R.string.prog_list_dial__no_fav_err), Toast.LENGTH_LONG)
                                .show();
                    } else {
                        startProgramActivity(true);
                    }
                } else {
                    startProgramActivity(false);
                }
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private void initResources(boolean performFullUpdate) {
        Log.d(TAG, "start parsing, performFullUpdate=" + performFullUpdate);
        setContentView(R.layout.loading);
        new InitResourcesTask(performFullUpdate, callback).execute();
    }

    public static MainActivity getInstance() {
        return parentActivity;
    }

    public ArrayList<Program> getProgramsData() {
        return programsData;
    }

    private void startProgramActivity(boolean onlyFavourites) {
        Intent i;
        if (GlobalInfo.USE_SIMPLE_STATIONS_VIEW) {
            i = new Intent(this, ProgramsListSelect.class);
        } else {
            i = new Intent(this, ImageScroller.class);
        }
        i.putExtra(PROGRAMS_FAV_OPT, onlyFavourites);
        startActivity(i);
    }

    private void prepareStartingDialog() {
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case DialogInterface.BUTTON_POSITIVE :
                        initResources(true);
                        break;
                    case DialogInterface.BUTTON_NEGATIVE :
                        initResources(false);
                        break;
                }
            }
        };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder
                .setMessage("Perform synchronization with server now?")
                .setPositiveButton("Yes", dialogClickListener)
                .setNegativeButton("No", dialogClickListener);
        builder.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                MainActivity.this.finish();
            }
        });
        builder.show();
    }

    private void prepareMenuButtonsListener() {
        Button program = (Button) findViewById(R.id.program);
        Button options = (Button) findViewById(R.id.options);
        Button about = (Button) findViewById(R.id.about);
        Button exit = (Button) findViewById(R.id.exit);
        program.setOnClickListener(menuListener);
        options.setOnClickListener(menuListener);
        about.setOnClickListener(menuListener);
        exit.setOnClickListener(menuListener);
    }

    private void prepareCallback() {
        callback = new MyXmlParserTaskCallback() {

            @Override
            public void onSuccess(ArrayList<Program> programs) {
                programsData = programs;
                setContentView(R.layout.main_menu);
                prepareMenuButtonsListener();
            }

            @Override
            public void onError(final Exception exception) {
                MainActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        MainActivity.this.setContentView(R.layout.plain_error);
                    }
                });
            }
        };
    }

    private void saveSharedPref() {
        Log.v(TAG, "saveSharedPref");
        if (favouritesList == null) {
            return;
        }
        SharedPreferences pref = getSharedPreferences(getResources().getString(R.string.app_name), Context.MODE_PRIVATE);
        Editor ed = pref.edit();
        ed.clear();
        ed.putInt(GlobalInfo.FAV_LIST_COUNT, favouritesList.size());
        Log.v(TAG, "saveSharedPref, items size=" + favouritesList.size());
        int i = 0;
        for (Iterator<String> iterator = favouritesList.iterator(); iterator.hasNext();) {
            String prog = iterator.next();
            ed.putString(PROGRAM_PREF_TAG + i++, prog);
            Log.v(TAG, "saveSharedPref, put item=" + prog);
        }
        ed.commit();
    }

    private void loadSharedPref() {
        Log.v(TAG, "loadSharedPref");
        if (favouritesList == null) {
            favouritesList = new ArrayList<String>();
        } else {
            favouritesList.clear();
        }
        SharedPreferences pref = getSharedPreferences(getResources().getString(R.string.app_name), Context.MODE_PRIVATE);
        int favCount = pref.getInt(GlobalInfo.FAV_LIST_COUNT, 0);
        Log.v(TAG, "loadSharedPref, count=" + favCount);
        for (int i = 0; i < favCount; ++i) {
            String prog = pref.getString(PROGRAM_PREF_TAG + i, null);
            if (prog != null) {
                favouritesList.add(prog);
                Log.v(TAG, "loadSharedPref, add to list=" + prog);
            }
        }
    }

    public void addToFavourites(String programName) {
        if (favouritesList == null) {
            favouritesList = new ArrayList<String>();
        }
        favouritesList.add(programName);
        saveSharedPref();
    }

    public void removeFromFavourites(String programName) {
        if (favouritesList == null) {
            return;
        }
        favouritesList.remove(programName);
        saveSharedPref();
    }

    public boolean isOnFavouritesList(String programName) {
        if (favouritesList == null) {
            return false;
        }
        for (Iterator<String> iterator = favouritesList.iterator(); iterator.hasNext();) {
            String prog = iterator.next();
            if (programName.equalsIgnoreCase(prog)) {
                return true;
            }
        }
        return false;
    }

    public List<String> getFavouritesList() {
        return favouritesList;
    }
}